""" -*- coding: utf-8 -*-"""
from flask import Blueprint, request, jsonify
from models import db, ProjectType, DesignPhase, FileType

misc_bp = Blueprint('misc', __name__)


# 项目类型管理
@misc_bp.route('/project_types', methods=['POST'], url_prefix='/misc')
def create_project_type():
    """创建项目类型"""
    data = request.get_json()
    if not data or 'name' not in data:
        return jsonify({'error': 'Missing required field: name'}), 400

    # 检查名称是否已存在
    if ProjectType.query.filter_by(name=data['name']).first():
        return jsonify({'error': 'Project type name already exists'}), 409

    new_type = ProjectType(
        name=data['name'],
        description=data.get('description', '')
    )

    try:
        db.session.add(new_type)
        db.session.commit()
        return jsonify({
            'message': 'Project type created successfully',
            'project_type': new_type.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'Database error: {str(e)}'}), 500


@misc_bp.route('/project_types', methods=['GET'])
def get_project_types():
    """获取所有项目类型"""
    types = ProjectType.query.all()
    return jsonify({
        'count': len(types),
        'project_types': [t.to_dict() for t in types]
    })


# 设计阶段管理
@misc_bp.route('/design_phases', methods=['POST'])
def create_design_phase():
    """创建设计阶段"""
    data = request.get_json()
    if not data or 'name' not in data:
        return jsonify({'error': 'Missing required field: name'}), 400

    # 检查名称是否已存在
    if DesignPhase.query.filter_by(name=data['name']).first():
        return jsonify({'error': 'Design phase name already exists'}), 409

    new_phase = DesignPhase(
        name=data['name'],
        description=data.get('description', '')
    )

    try:
        db.session.add(new_phase)
        db.session.commit()
        return jsonify({
            'message': 'Design phase created successfully',
            'design_phase': new_phase.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'Database error: {str(e)}'}), 500


@misc_bp.route('/design_phases', methods=['GET'])
def get_design_phases():
    """获取所有设计阶段"""
    phases = DesignPhase.query.all()
    return jsonify({
        'count': len(phases),
        'design_phases': [p.to_dict() for p in phases]
    })


# 文件类型管理
@misc_bp.route('/file_types', methods=['POST'])
def create_file_type():
    """创建文件类型"""
    data = request.get_json()
    required_fields = ['name', 'design_phase_id']
    for field in required_fields:
        if field not in data:
            return jsonify({'error': f'Missing required field: {field}'}), 400

    # 检查设计阶段是否存在
    if not DesignPhase.query.get(data['design_phase_id']):
        return jsonify({'error': 'Design phase not found'}), 404

    # 检查名称是否已存在
    if FileType.query.filter_by(name=data['name']).first():
        return jsonify({'error': 'File type name already exists'}), 409

    new_type = FileType(
        name=data['name'],
        design_phase_id=data['design_phase_id'],
        description=data.get('description', '')
    )

    try:
        db.session.add(new_type)
        db.session.commit()
        return jsonify({
            'message': 'File type created successfully',
            'file_type': new_type.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'Database error: {str(e)}'}), 500


@misc_bp.route('/file_types', methods=['GET'])
def get_file_types():
    """获取所有文件类型"""
    types = FileType.query.all()
    return jsonify({
        'count': len(types),
        'file_types': [t.to_dict() for t in types]
    })